package com.feng.financial.seller.service;

import com.feng.financial.common.querydsl.FetchResponse;
import com.feng.financial.common.querydsl.FetchResponseBuilder;
import com.feng.financial.common.web.Range;
import com.feng.financial.entity.OrderTEntity;
import com.feng.financial.entity.QOrderTEntity;
import com.feng.financial.seller.repository.OrderTRepository;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Objects;

/**
 * @author Administrator
 */
@Service
public class OrderTService {

    @Autowired
    private OrderTRepository orderTRepository;

    @PersistenceContext
    private EntityManager em;

    @Transactional
    public OrderTEntity saveOrder(OrderTEntity orderTEntity){
        return orderTRepository.save(orderTEntity);
    }

    public FetchResponse<OrderTEntity> findAllByPage(OrderTEntity order, Range range){
        QOrderTEntity qOrderTEntity = QOrderTEntity.orderTEntity;
        JPAQuery<OrderTEntity> query = new JPAQueryFactory(em).select(qOrderTEntity).from(qOrderTEntity);
        if (!Objects.isNull(order.getOrderType())) query = query.where(qOrderTEntity.orderType.eq(order.getOrderType()));
        if (!Objects.isNull(order.getOrderId())) query = query.where(qOrderTEntity.orderId.eq(order.getOrderId()));
        return new FetchResponseBuilder<OrderTEntity>().range(range).build(query);
    }

}
